import sun.security.krb5.internal.Ticket;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @projectName: java-daily-questions
 * @package: PACKAGE_NAME
 * @className: SellTicket
 * @author: ZM
 * @description: condition - 实现售票
 * @date: 2021/8/27 13:14
 * @version: 1.0
 */
public class SellTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket(0);
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();

        new Thread(()->{
            try {
                while (true) {
                    reentrantLock.lock();
                    while (ticket.getTicketNum() <= 0) {
                        // 票不足，进入等待队列
                        condition.await();
                    }
                    ticket.sale();
                    System.out.println("出售一张票，目前剩余：" + ticket.getTicketNum());

                    // 唤醒一个等待的线程
                    condition.signal();
                    TimeUnit.MILLISECONDS.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }).start();

        new Thread(()->{
            try {
                while (true) {
                    reentrantLock.lock();
                    while (ticket.getTicketNum() >= 10) {
                        // 票已满，进入等待队列
                        condition.await();
                    }
                    ticket.recycle();
                    System.out.println("回收一张票，目前剩余：" + ticket.getTicketNum());

                    // 唤醒一个等待线程
                    condition.signal();
                    TimeUnit.MILLISECONDS.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }).start();

    }

    static class Ticket {
        private int ticketNum;
        public Ticket(int ticketNum) {
            this.ticketNum = ticketNum;
        }
        public int getTicketNum() {
            return ticketNum;
        }
        public void sale() {
            ticketNum--;
        }
        public void recycle() {
            ticketNum++;
        }
    }
}
